<?php 
/**
 * QFrameWork
 *
 * @author: quyang
 * @date: 2010-1-17
 * @version: 1.0
 */

 
class String {
    /**
     * 取字符串宽度 中文算两个字符长
     * unicode 算作 4字符长度
     *
     * @param string $str
     * @return int
     */
    function str_width($str) {
        $str = preg_replace("/&(#\d{3,5});/", "__", $str);
        $str = preg_replace("/&([a-z]{2,7});/", "_", $str);
        return mb_strwidth($str, 'UTF-8');
    }
    
    /**
     * 字符串截取 按字符长度进行截取
     * 例：标题长度限制为8字符宽，用本函数进行截取
     *
     * @param string $str       //被截断的字串
     * @param int $start        //截断启始点
     * @param int $offset       //截断长度
     * @param string $suffix    //...
     * @return string
     */
    function substr($str, $start, $offset, $suffix = '') {
        $rs = mb_strimwidth($str, $start, $offset, '', 'UTF-8');
        
        if (! empty($suffix)) {
            $rs .= $rs <> $str ? $suffix : '';
        }
        
        return $rs;
    }
    /**
     * 过滤字符串中的HTML标记 < >
     * @param string $str 需要过滤的字符
     * @return string
     */
    function un_html($str) {
        String::esc_ascii($str);
        
        $str = stripslashes($str);
        $s = array("&"=>"&amp;", "<"=>"&lt;", ">"=>"&gt;", "\n"=>"<br>", "\t"=>"&nbsp;&nbsp;&nbsp;&nbsp;", "\r"=>"", " "=>"&nbsp;", "\""=>"&quot;", "'"=>"&#039;", );
        $str = strtr($str, $s);
        return $str;
    }
    /**
     * 过滤空字符
     *
     * @param string $str
     * @return string
     */
    function esc_ascii($str) {
        $esc_ascii_table = array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7), chr(8), chr(11), chr(12), chr(14), chr(15), chr(16), chr(17), chr(18), chr(19), chr(20), chr(21), chr(22), chr(23), chr(24), chr(25), chr(26), chr(27), chr(28), chr(29), chr(30), chr(31));
        
        $str = str_replace($esc_ascii_table, '', $str);
        return $str;
    }
    /**
     * 转化URL为链接
     *
     * @param string $string
     * @return string
     */
    function url2link($string) {
        $string = preg_replace("/(^|\s|[^\w])([\.\w\-]+\@[\.\w\-]+\.[\.\w\-]+)/i", "\\1<a href=\"mailto:\\2\">\\2</a>", $string);
        
        $string = preg_replace("/(^|\s)((http|https|news|ftp):\/\/\w+[^\s<>\[\]]+)/i", "<a href=\"\\2\" target=\"_blank\">\\2</a>", $string);
        return $string;
    }
}
?>
